from flask import abort, jsonify
from flask import current_app
from flask import g
from flask import request
from flask import session

from info import db
from info.models import User, News, Comment, CommentLike
from info.modules.news import news_blue
from flask import render_template

from info.utils.commons import user_login_data
from info.utils.response_code import RET


@news_blue.route('/<int:news_id>')
@user_login_data
def news(news_id):
    # user_id = session.get('user_id')
    # user = None
    # if not user:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)


    try:
        news = News.query.get(news_id)
    except Exception as e :
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='获取新闻失败')

    if news == None:
        abort(404)


    try:
        click_news_list = News.query.order_by(News.clicks).limit(10).all()
    except Exception as e:
        current_app.logger.error(e)

    dict_news = []

    for news_click in click_news_list:
        dict_news.append(news_click.to_dict())


    is_collected = False

    if g.user and news in g.user.collection_news:
        is_collected = True

    is_followed = False
    if news.user and g.user in news.user.followers:
        is_followed = True

    #查询当前新闻的所有评论

    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='查询失败')


    #点赞处理
    comment_likes = []
    if g.user:
        comment_likes = CommentLike.query.filter(CommentLike.user_id == g.user.id).all()

    comment_like_ids = []

    for comment_like in comment_likes:
        comment_like_ids.append(comment_like.comment_id)

    comments_list = []

    for comment in comments:
        comm_dict = comment.to_dict()
        comm_dict["is_like"] = False

        if g.user and comment.id in comment_like_ids:
            comm_dict["is_like"] = True

        comments_list.append(comm_dict)




    dict_data ={

        'user_info': g.user.to_dict() if g.user else '',
        'news_info' : news.to_dict(),
        'click_news_list' : dict_news,
        'is_collected': is_collected,
        'comments': comments_list,
        'is_followed':is_followed
    }



    return render_template('news/detail.html',dict_data = dict_data)

@news_blue.route('/news_collect' , methods=['POST'])
@user_login_data
def news_collect():

    if not g.user:
        return jsonify(errno=RET.PARAMERR,errmsg='请登录')

    news_id = request.json.get('news_id')
    action = request.json.get('action')

    try:
        news = News.query.get(news_id)
    except Exception as e :
        current_app.logger.error(e)
        return jsonify(errno=RET.NODATA,errmsg='新闻不存在')

    if not action in ['collect','cancel_collect']:
        return jsonify(errno=RET.DATAERR,errmsg='操作失误')

    if action  == 'collect':
        if news not in g.user.collection_news:
            g.user.collection_news.append(news)
            db.session.commit()

            return jsonify(errno=RET.OK, errmsg='收藏成功')
    else:
        if news  in g.user.collection_news:
            g.user.collection_news.remove(news)
            db.session.commit()

            return jsonify(errno=RET.OK, errmsg='取消收藏成功')


    return jsonify(errno=RET.OK, errmsg='操作成功')


@news_blue.route('/news_comment',methods=['POST'])
@user_login_data
def news_comment():

    if not g.user:
        return jsonify(errno=RET.PARAMERR,errmsg='请登录')

    news_id = request.json.get('news_id')
    content = request.json.get('comment')
    parent_id = request.json.get('parent_id')

    if not all([news_id,content]):
        return jsonify(errno=RET.DBERR,errmsg='参数不全')

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='查询失败')

    if not news:
        return jsonify(errno=RET.DBERR,errmsg='新闻不存在')

    comment = Comment()
    comment.user_id = g.user.id
    comment.news_id = news_id
    comment.content = content

    if parent_id:
        comment.parent_id = parent_id

    try:
        db.session.add(comment)
        db.session.commit()

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='评论失败')

    return jsonify(errno=RET.OK, errmsg='操作成功' , dict_data=comment.to_dict())


@news_blue.route('/comment_like', methods=['POST'])
@user_login_data
def comment_like():

    if not g.user:
        return jsonify(errno=RET.PARAMERR,errmsg="用户未登录")

    comment_id = request.json.get("comment_id")
    action = request.json.get("action")

    if not all([comment_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")

    if not action in ["add","remove"]:
        return jsonify(errno=RET.DATAERR,errmsg="操作类型有误")

    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询评论有误")

    if not comment:
        return jsonify(errno=RET.NODATA,errmsg="评论不存在")


    try:
        if action == "add":

            comment_like = CommentLike.query.filter(CommentLike.user_id == g.user.id,CommentLike.comment_id == comment_id).first()

            if not comment_like:
                comment_like = CommentLike()
                comment_like.comment_id = comment_id
                comment_like.user_id = g.user.id

                db.session.add(comment_like)

                comment.like_count += 1
                db.session.commit()
        else:
            comment_like = CommentLike.query.filter(CommentLike.user_id == g.user.id,
                                                    CommentLike.comment_id == comment_id).first()

            if comment_like:
                db.session.delete(comment_like)

                if comment.like_count > 0:
                    comment.like_count -= 1

                db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="操作失败")

    return jsonify(errno=RET.OK,errmsg="操作成功")


@news_blue.route('/followed_user', methods=['POST'])
@user_login_data
def followed_user():

    if not g.user:
        return jsonify(errno=RET.NODATA,errmsg="用户未登录")

    author_id = request.json.get("user_id")
    action = request.json.get("action")


    if not all([author_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")


    if not action in ["follow","unfollow"]:
        return jsonify(errno=RET.DATAERR,errmsg="操作类型有误")

    try:
        author = User.query.get(author_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取作者失败")

    if not author:
        return jsonify(errno=RET.NODATA,errmsg="作者不存在")

    if action == "follow":
        if g.user not in author.followers:
            author.followers.append(g.user)
    else:
        if g.user in author.followers:
            author.followers.remove(g.user)


    return jsonify(errno=RET.OK,errmsg="success")












